package com.npr.controller;

import com.npr.entity.DiscussPost;
import com.npr.entity.Page;
import com.npr.entity.User;
import com.npr.service.DiscussPostService;
import com.npr.service.LikeService;
import com.npr.service.UserService;
import com.npr.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主页控制器
 */
@Controller
public class HomeController implements CommunityConstant {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;
    //将帖子信息和对应的用户信息装入到map中，再将map加入到arraylist中
    @RequestMapping(path ="/index",method = RequestMethod.GET)
    public String getIndextPage(Model model, Page page,@RequestParam(name = "orderMode",defaultValue = "0") int orderMode){
        //方法调用之前，Spirngmvc会自动实例化Model和Page，并将Page注入到Model
        //所以在Thymleaf中可以直接访问Page对象中的数据
        page.setRows(discussPostService.findDiscussPostRows(0));
        page.setPath("/index?orderMode="+orderMode);
        List<DiscussPost> list = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit(),orderMode);
        ArrayList<Map<String,Object>> discussPosts = new ArrayList<>();
        if(list !=null){
            for (DiscussPost post : list) {
                Map<String,Object> map = new HashMap<>();
                map.put("post",post);
                User user = userService.findUserById(post.getUserId());
                map.put("user",user);
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST,post.getId());
                map.put("likeCount",likeCount);

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        model.addAttribute("orderMode",orderMode);
        return "/index";
    }
    @RequestMapping(path="/error",method=RequestMethod.GET)
    public String getErrorPage(){
        return "/error/500";
    }
}
